package com.banmao.algorithm.No101To200.No114;

import java.util.ArrayList;

// 低效率的遍历方式
public class Solution {

    private ArrayList<TreeNode> list = new ArrayList<>();

    public void flatten(TreeNode root) {
        if(root == null) return;

        // 先序遍历
        preTraversal(root);

        // 按list的顺序将tree置为链表
        for (int i = 0; i < list.size(); i++) {
            TreeNode cur = list.get(i);
            if(i == list.size() - 1) {
                cur.left = null;
                cur.right = null;
                continue;
            }

            cur.left = null;
            cur.right = list.get(i + 1);

        }

    }

    private void preTraversal(TreeNode root) {
        if(root == null) return;

        list.add(root);

        preTraversal(root.left);
        preTraversal(root.right);

    }

}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
